package lesson.subject;

import lesson.db.DbUtil;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class SubjectService {



    /**
     * 保存学科
     * @param name
     */
    public String saveSubject(Integer id, String name) {

        if (checkExist(id, name)) {
            return "该名称的学科已存在";
        }

        if (id == null) {
            SqlSession session = DbUtil.getSession(true);
            try{
                SubjectDao subjectDao = session.getMapper(SubjectDao.class);
                subjectDao.addSubject(name);

            }finally {
                session.close();

            }

        } else {
            SqlSession session = DbUtil.getSession(true);
            try{

                SubjectDao subjectDao = session.getMapper(SubjectDao.class);
                subjectDao.updateSubject(id, name);
            }finally {

                session.close();
            }
        }

        return null;

    }


    /**
     * 检测叫这个名字的用户是否存在
     * @param name
     * @return
     */
    public boolean checkExist(Integer exceptId, String name) {
        SqlSession session = DbUtil.getSession(true);
        try{
            SubjectDao subjectDao = session.getMapper(SubjectDao.class);
            boolean exist = subjectDao.checkExist(exceptId,name);
            return exist;

        }finally {
            session.close();

        }
    }

    /**
     * 根据关键字查询
     * @param keywords
     * @return
     */
    public List<Subject> list(String keywords) {
        SqlSession session = DbUtil.getSession(true);
        try {
            SubjectDao subjectDao = session.getMapper(SubjectDao.class);
            List<Subject> list = subjectDao.list(keywords);
            return list;
        }finally {

            session.close();
        }

    }


    public String del(Integer id) {
        SqlSession session = DbUtil.getSession(true);
        try{
            SubjectDao subjectDao = session.getMapper(SubjectDao.class);
            subjectDao.delSubject(id);
            return null;

        }finally {
            session.close();

        }

    }

    public Subject getById(Integer id) {
        SqlSession session = DbUtil.getSession(true);
        try{
            SubjectDao subjectDao = session.getMapper(SubjectDao.class);
            Subject subject = subjectDao.getById(id);
            return subject;
        }finally {

            session.close();
        }

    }
}
